#include"heap.h"

void Hinit(Heap* php)
{
	assert(php);
	php->a = NULL;
	php->capacity = php->size = 0;
}

void Hdestory(Heap* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->capacity = php->size = 0;
}

void Hpush(Heap* php, Hdatetype x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int Newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		Hdatetype* tmp = (Hdatetype*)realloc(php->a, Newcapacity * sizeof(Hdatetype));
		if (tmp == NULL)
		{
			perror("relloc:");
			exit(-1);
		}
		php->a = tmp;
		php->capacity = Newcapacity;
	}
	php->a[php->size] = x;
	php->size++;
}

void Hpop(Heap* php)
{
	assert(php);
	assert(!Hempty(php));
	Swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;
}

Hdatetype Htop(Heap* php)
{
	assert(php);
	assert(!Hempty(php));
	return php->a[0];
}

bool Hempty(Heap* php)
{
	assert(php);
	return php->size == 0;
}

int Hsize(Heap* php)
{
	assert(php);
	return php->size;
}

void Adjustup(Hdatetype* a, int size)
{
	assert(a);
	int child = size - 1;
	int par = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[par])
		{
			Swap(&a[child], &a[par]);
			child = par;
			par = (child - 1) / 2;
		}
		else
			break;
	}
}

void Adjustdown(Hdatetype* a, int size, int par)
{
	assert(a);
	int child = par * 2 + 1;
	while (child < size)
	{
		if (child + 1 < size && a[child + 1] > a[child])
		{
			child++;
		}
		if (a[par] < a[child])
		{
			Swap(&a[child], &a[par]);
			par = child;
			child = par * 2 + 1;
		}
		else
			break;
	}
}

void Swap(Hdatetype* date1, Hdatetype* date2)
{
	assert(date1 && date2);
	Hdatetype tmp = *date1;
	*date1 = *date2;
	*date2 = tmp;
}

